import axios from 'axios'
import { router } from '../router'
//后台响应超时设置
axios.defaults.timeout = 60000;
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';

//请求拦截器
axios.interceptors.request.use(config => {
    let token = localStorage.getItem('userinfo');
    let dataObj = JSON.parse(token);
    let nowTime = new Date().getTime()
    let exp = 1000 * 60 * 60 * 24; // 24个小时
    if (token) {
        if (nowTime - dataObj.time > exp) {
            localStorage.clear('userinfo')
            router.push({ path: "/login" })
        } else {
            config.headers['authorization'] = dataObj.data;
        }
    }
    return config
}, error => {
    return Promise.reject(error)
});
//响应拦截器
axios.interceptors.response.use(response => {
    let code = response.data.code;
    let curTime = new Date().getTime();
    let account = '';
    let userToken = '';
    if (code === 2000) {
        if (response.data.data) {
            account = response.data.data.account;
            userToken = response.data.data.authorization;
        }
        let resUrl = response.config.url;
        let targetUrlStrOfPart = "user/login";
        if (resUrl.indexOf(targetUrlStrOfPart) != -1) {
            localStorage.setItem('userinfo', JSON.stringify({ data: userToken, time: curTime }));
            localStorage.setItem('account', account)
        }
        return response
    } else if (code === 5001) {
        // alert('请求失败')
        router.push({ path: "/login" })
    }
    return response
}, error => {
    return Promise.reject(error)
});
